package com.kuang.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {

    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "Hello Shiro");
        return "index";
    }

    @RequestMapping("/user/toAdd")
    public String toAdd() {
        return "user/add";
    }

    @RequestMapping("/user/toUpdate")
    public String toUpdate() {
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model) {

        System.out.println("===========>"+username);
        System.out.println("===========>"+password);

        //获取subject
        Subject user = SecurityUtils.getSubject();

        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            user.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            //用户名错误
            model.addAttribute("msg","用户名错误!!!");
            return "login";
        }catch (IncorrectCredentialsException e){
            //密码错误
            model.addAttribute("msg","密码错误!!!");
            return "login";
        }

    }

    @RequestMapping("/noAuth")
    public String author(){
        return "noAuth";
    }
}
